package com.taysear.parcel.fieldfactory;

import com.taysear.parcel.ParcelApplication;
import com.taysear.parcel.domain.Employee;
import com.taysear.parcel.util.Constants;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
import com.vaadin.addon.jpacontainer.fieldfactory.FieldFactory;
import com.vaadin.data.Item;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.Field;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;

public class UserFieldFactory extends FieldFactory {
	
	ParcelApplication app;
	public final TextField userId = new TextField("User id");
	public final TextField username = new TextField("Username");
	final PasswordField password = new PasswordField("Password");
	final ComboBox employee = new ComboBox("Employee");

	public UserFieldFactory(ParcelApplication app) {
		this.app = app;
	}

	@Override
	public Field createField(Item item, Object propertyId, Component uiContext) {
		Field f;
		if ("userId".equals(propertyId)) {
			userId.setRequired(true);
			userId.setWidth(Constants.COMMON_FIELD_WIDTH);
			return userId;
		} if ("username".equals(propertyId)) {
			username.setRequired(true);
			username.setWidth(Constants.COMMON_FIELD_WIDTH);
			username.setRequiredError("Username is required");
			username.setNullRepresentation("");
			return username;
		} if ("password".equals(propertyId)) {
			password.setRequired(true);
			password.setWidth(Constants.COMMON_FIELD_WIDTH);
			password.setRequiredError("Password is required");
			password.setNullRepresentation("");
			return password;
		} if ("employee".equals(propertyId)) {
			JPAContainer<Employee> senderStationContainer = JPAContainerFactory.make(Employee.class, app.PERSISTENCE_UNIT);
			employee.setContainerDataSource(senderStationContainer);
			employee.setWidth(Constants.COMMON_FIELD_WIDTH);
			employee.setNullSelectionAllowed(false);
			employee.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_ITEM);
			employee.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH);
			employee.setRequired(true);
			employee.setRequiredError("Employee is required");
			return employee;
		} else {
			// Use the super class to create a suitable field base on the
			// property type.
			f = super.createField(item, propertyId, uiContext);
		}
		return f;
	}
}
